/**
 * Copyright 2016 JustWayward Team
 * <p/>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p/>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p/>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hzf.booklibrary.ui.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.ListPopupWindow;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.hzf.booklibrary.R;
import com.hzf.booklibrary.base.BaseActivity;
import com.hzf.booklibrary.base.Constant;
import com.hzf.booklibrary.bean.BookSource;
import com.hzf.booklibrary.bean.BookToc;
import com.hzf.booklibrary.bean.ChapterRead;
import com.hzf.booklibrary.bean.Recommend;
import com.hzf.booklibrary.bean.book.Book;
import com.hzf.booklibrary.bean.support.DownloadMessage;
import com.hzf.booklibrary.bean.support.DownloadProgress;
import com.hzf.booklibrary.bean.support.ReadTheme;
import com.hzf.booklibrary.component.AppComponent;

import com.hzf.booklibrary.component.DaggerBookComponent;
import com.hzf.booklibrary.manager.CacheManager;
import com.hzf.booklibrary.manager.SettingManager;
import com.hzf.booklibrary.manager.ThemeManager;
import com.hzf.booklibrary.ui.adapter.TocListAdapter;
import com.hzf.booklibrary.ui.contract.BookReadContract;
import com.hzf.booklibrary.ui.easyadapter.ReadThemeAdapter;
import com.hzf.booklibrary.ui.presenter.BookReadPresenter;
import com.hzf.booklibrary.utils.LogUtils;
import com.hzf.booklibrary.utils.ScreenUtils;
import com.hzf.booklibrary.utils.SharedPreferencesUtil;
import com.hzf.booklibrary.utils.ToastUtils;
import com.hzf.booklibrary.view.readview.BaseReadView;
import com.hzf.booklibrary.view.readview.OnReadStateChangeListener;
import com.hzf.booklibrary.view.readview.OverlappedWidget;
import com.hzf.booklibrary.view.readview.PageWidget;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.inject.Inject;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Created by lfh on 2016/9/18.
 */
public class ReadActivity extends BaseActivity implements BookReadContract.View {

    @Bind(R.id.flReadWidget)
    FrameLayout flReadWidget;//阅读页面

    @Bind(R.id.reBookReadTop)
    RelativeLayout mLlBookReadTop;//顶部状态栏
//    @Bind(R.id.ibBackTop)
//    ImageView mIvBack;//返回
    @Bind(R.id.tvBookReadTocTitle)
    TextView mTvBookReadTocTitle;//章节名称
    @Bind(R.id.ibBookReadToc)
    ImageButton mTvBookReadToc;//图书章节列表

    @Bind(R.id.rlBookReadRoot)
    RelativeLayout mRlBookReadRoot;//阅读整个界面根标签
    @Bind(R.id.rlReadAaSet)
    LinearLayout rlReadAaSet;//底部设置栏

    @Bind(R.id.tvFontsizeMinus)
    TextView tvFontsizeMinus;//调小字体
    @Bind(R.id.seekbarFontSize)
    SeekBar seekbarFontSize;//字体大小进度条
    @Bind(R.id.tvFontsizePlus)
    TextView tvFontsizePlus;//调大字体
    @Bind(R.id.mRadioGroup)
    RadioGroup mRadioGroup;//设置分页效果
    @Bind(R.id.gvTheme)
    GridView gvTheme;//阅读风格

    private View decodeView;

    @Inject
    BookReadPresenter mPresenter;

    private List<BookToc.mixToc.Chapters> mChapterList = new ArrayList<BookToc.mixToc.Chapters>();
    private ListPopupWindow mTocListPopupWindow;
    private TocListAdapter mTocListAdapter;

    private int currentChapter = 1;

    /**
     * 是否开始阅读章节
     **/
    private boolean startRead = false;
    private BaseReadView mPageWidget;
    private int curTheme = -1;
    private List<ReadTheme> themes;
    private ReadThemeAdapter gvAdapter;
    private Receiver receiver = new Receiver();
    private IntentFilter intentFilter = new IntentFilter();
    private SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");

    public static final String INTENT_BEAN = "recommendBooksBean";
    public static final String INTENT_SD = "isFromSD";

    private Book recommendBooks;
    private String bookId;

    private boolean isFromSD = false;

    //添加收藏需要，所以跳转的时候传递整个实体类
    public static void startActivity(Context context, Book recommendBooks) {
        startActivity(context, recommendBooks, false);
    }

    public static void startActivity(Context context, Book recommendBooks, boolean isFromSD) {
        context.startActivity(new Intent(context, ReadActivity.class)
                .putExtra(INTENT_BEAN, recommendBooks)
                .putExtra(INTENT_SD, isFromSD));
    }

    @Override
    public int getLayoutId() {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        statusBarColor = ContextCompat.getColor(this, R.color.reader_menu_bg_color);
        return R.layout.activity_read;
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerBookComponent.builder()
                .appComponent(appComponent)
                .build()
                .inject(this);
    }
    @Override
    public void initTitleBar() {}

    @Override
    public void initDatas() {
        recommendBooks = (Book) getIntent().getSerializableExtra(INTENT_BEAN);
        recommendBooks.isFromSD = true;
        bookId = recommendBooks.id;
        //直接走本地图书读取流程 line257，不走网络图书流程
        isFromSD = true;
        EventBus.getDefault().register(this);
        showDialog();
        mTvBookReadTocTitle.setText(recommendBooks.name);

    //    intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
        intentFilter.addAction(Intent.ACTION_TIME_TICK);

    }

    @Override
    public void configViews() {
        hideStatusBar();
        decodeView = getWindow().getDecorView();
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mLlBookReadTop.getLayoutParams();
        params.topMargin = ScreenUtils.getStatusBarHeight(this) - 2;
        mLlBookReadTop.setLayoutParams(params);
        //目录
        initTocList();
        //调整字体大小
        initAASet();
         //页对象
        initPagerWidget();
        mPresenter.attachView(this);
        // 本地收藏  直接打开
        if (isFromSD) {
            BookToc.mixToc.Chapters chapters = new BookToc.mixToc.Chapters();
            chapters.title = recommendBooks.name;
            mChapterList.add(chapters);
            showChapterRead(null, currentChapter);
            return;
        }
        mPresenter.getBookToc(bookId, "chapters");
    }


    private void initTocList() {
        mTocListAdapter = new TocListAdapter(this, mChapterList, bookId, currentChapter);
        mTocListPopupWindow = new ListPopupWindow(this);
        mTocListPopupWindow.setAdapter(mTocListAdapter);
        mTocListPopupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        mTocListPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        mTocListPopupWindow.setAnchorView(mLlBookReadTop);
        mTocListPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mTocListPopupWindow.dismiss();
                currentChapter = position + 1;
                mTocListAdapter.setCurrentChapter(currentChapter);
                startRead = false;
                showDialog();
                readCurrentChapter();
                hideReadBar();
            }
        });
        mTocListPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                gone(mTvBookReadTocTitle);
            }
        });
    }

    private void initAASet() {
        //阅读字体
        seekbarFontSize.setMax(10);
        //int fontSizePx = SettingManager.getInstance().getReadFontSize(bookId);
        int fontSizePx = SettingManager.getInstance().getReadFontSize();
        int progress = (int) ((fontSizePx- getResources().getDimensionPixelSize(R.dimen.dimen_12dp)) / 1.7f);
        seekbarFontSize.setProgress(progress);
        seekbarFontSize.setOnSeekBarChangeListener(new SeekBarChangeListener());
        //阅读背景样式
        curTheme = SettingManager.getInstance().getReadTheme();
        ThemeManager.setReaderTheme(curTheme, mRlBookReadRoot);
        gvAdapter = new ReadThemeAdapter(this, (themes = ThemeManager.getReaderThemeData(curTheme)), curTheme);
        gvTheme.setAdapter(gvAdapter);
        gvTheme.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position < themes.size() - 1) {
                    changedMode(position);
                } else {
                    changedMode(position);
                }
            }
        });
        //翻页效果
        switch (SharedPreferencesUtil.getInstance().getInt(Constant.FLIP_STYLE, 0)){
            case 1:
                mRadioGroup.check(R.id.rb_slide);
                break;
            case 0:
                mRadioGroup.check(R.id.rb_simulation);
                break;
        }
        mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                switch (i){
                    case R.id.rb_slide://滑动效果
                        SharedPreferencesUtil.getInstance().putInt(Constant.FLIP_STYLE,1);
                        break;
                    case R.id.rb_simulation://仿真效果
                        SharedPreferencesUtil.getInstance().putInt(Constant.FLIP_STYLE,0);
                        break;
                }
                initPagerWidget();//重新设置BaseReadView对象
                mPageWidget.init(curTheme);//初始化
            }
        });
    }

    private void initPagerWidget() {
        if (SharedPreferencesUtil.getInstance().getInt(Constant.FLIP_STYLE, 0) == 0) {
            mPageWidget = new PageWidget(this, bookId, mChapterList, new ReadListener());
        } else {
            mPageWidget = new OverlappedWidget(this, bookId, mChapterList, new ReadListener());
        }
        registerReceiver(receiver, intentFilter);
        if (SharedPreferencesUtil.getInstance().getBoolean(Constant.ISNIGHT, false)) {
            mPageWidget.setTextColor(ContextCompat.getColor(this, R.color.chapter_content_night),
                    ContextCompat.getColor(this, R.color.chapter_title_night));
        }
        flReadWidget.removeAllViews();
        flReadWidget.addView(mPageWidget);
    }

    @Override
    public void showBookToc(List<BookToc.mixToc.Chapters> list) { // 加载章节列表
        mChapterList.clear();
        mChapterList.addAll(list);
        readCurrentChapter();
    }

    /**
     * 读取currentChapter章节。章节文件存在则直接阅读，不存在则请求
     */
    public void readCurrentChapter() {
        if (CacheManager.getInstance().getChapterFile(bookId, currentChapter) != null) {
            showChapterRead(null, currentChapter);
        } else {
            mPresenter.getChapterRead(mChapterList.get(currentChapter - 1).link, currentChapter);
        }
    }

    @Override
    public synchronized void showChapterRead(ChapterRead.Chapter data, int chapter) { // 加载章节内容
        if (data != null) {
            CacheManager.getInstance().saveChapterFile(bookId, chapter, data);
        }

        if (!startRead) {
            startRead = true;
            currentChapter = chapter;
            if (!mPageWidget.isPrepared) {
                mPageWidget.init(curTheme);
            } else {
                mPageWidget.jumpToChapter(currentChapter);
            }
            hideDialog();
        }
    }

    @Override
    public void showBookSource(List<BookSource> list) {}

    @Override
    public void netError(int chapter) {
        hideDialog();//防止因为网络问题而出现dialog不消失
        if (Math.abs(chapter - currentChapter) <= 1) {
            ToastUtils.showToast(R.string.net_error);
        }
    }

    @OnClick(R.id.ibBackTop)
    public void onClickBackTop() {
        if (mTocListPopupWindow.isShowing()) {
            mTocListPopupWindow.dismiss();
        } else {
            finish();
        }
    }
    @OnClick(R.id.ibBackBottom)
    public void onClickBackBottom() {
        if (mTocListPopupWindow.isShowing()) {
            mTocListPopupWindow.dismiss();
        } else {
            finish();
        }
    }
    private void changedMode(int position) {

        if (position >= 0) {
            curTheme = position;
        } else {
            curTheme = SettingManager.getInstance().getReadTheme();
        }
        gvAdapter.select(curTheme);

        mPageWidget.setTheme(curTheme);
        mPageWidget.setTextColor(ContextCompat.getColor(mContext,  R.color.chapter_content_day),
                ContextCompat.getColor(mContext, R.color.chapter_title_day));

        Drawable drawable = ContextCompat.getDrawable(this,  R.drawable.ic_menu_mode_day_manual);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        ThemeManager.setReaderTheme(curTheme, mRlBookReadRoot);
    }

    //调低字体
    @OnClick(R.id.tvFontsizeMinus)
    public void fontsizeMinus() {
        calcFontSize(seekbarFontSize.getProgress() - 1);
    }
    //调高字体
    @OnClick(R.id.tvFontsizePlus)
    public void fontsizePlus() {
        calcFontSize(seekbarFontSize.getProgress() + 1);
    }




    @Subscribe(threadMode = ThreadMode.MAIN)
        public void showDownProgress(DownloadProgress progress) {
//            if (bookId.equals(progress.bookId)) {
//                if (isVisible(mLlBookReadBottom)) { // 如果工具栏显示，则进度条也显示
//                    visible(mTvDownloadProgress);
//                    // 如果之前缓存过，就给提示
//                    mTvDownloadProgress.setText(progress.message);
//                } else {
//                    gone(mTvDownloadProgress);
//                }
//            }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void downloadMessage(final DownloadMessage msg) {
//        if (isVisible(mLlBookReadBottom)) { // 如果工具栏显示，则进度条也显示
//            if (bookId.equals(msg.bookId)) {
//                visible(mTvDownloadProgress);
//                mTvDownloadProgress.setText(msg.message);
//                if (msg.isComplete) {
//                    mTvDownloadProgress.postDelayed(new Runnable() {
//                        @Override
//                        public void run() {
//                            gone(mTvDownloadProgress);
//                        }
//                    }, 2500);
//                }
//            }
//        }
    }

    private synchronized void hideReadBar() {
        gone( mLlBookReadTop, rlReadAaSet);
        hideStatusBar();
        decodeView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
    }

    private synchronized void showReadBar() { // 显示工具栏
        visible(mLlBookReadTop,rlReadAaSet);
        Log.e("visible",mLlBookReadTop.getVisibility()+"");
        showStatusBar();
        //设置状态栏
        decodeView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
    }

    private void toggleReadBar() { // 切换工具栏 隐藏/显示 状态
        if (isVisible(mLlBookReadTop)) {
            hideReadBar();
        } else {
            showReadBar();
        }
    }

    @Override
    public void showError() {
        hideDialog();
    }

    @Override
    public void complete() {
        hideDialog();
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mTocListPopupWindow != null && mTocListPopupWindow.isShowing()) {
                mTocListPopupWindow.dismiss();
                gone(mTvBookReadTocTitle);
                return true;
            } else if (isVisible(rlReadAaSet)) {
                hideReadBar();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        SettingManager.getInstance().removeReadProgress(bookId);//移除阅读记录
        try {
            unregisterReceiver(receiver);
        } catch (Exception e) {
            LogUtils.e("Receiver not registered");
        }

        if (mPresenter != null) {
            mPresenter.detachView();
        }
    }

    class ReadListener implements OnReadStateChangeListener {
        @Override
        public void onChapterChanged(int chapter) {
            LogUtils.i("onChapterChanged:" + chapter);
            currentChapter = chapter;
            mTocListAdapter.setCurrentChapter(currentChapter);
            // 加载前一节 与 后三节
            for (int i = chapter - 1; i <= chapter + 3 && i <= mChapterList.size(); i++) {
                if (i > 0 && i != chapter
                        && CacheManager.getInstance().getChapterFile(bookId, i) == null) {
                    mPresenter.getChapterRead(mChapterList.get(i - 1).link, i);
                }
            }
        }

        @Override
        public void onPageChanged(int chapter, int page) {
            LogUtils.i("onPageChanged:" + chapter + "-" + page);
        }

        @Override
        public void onLoadChapterFailure(int chapter) {
            LogUtils.i("onLoadChapterFailure:" + chapter);
            startRead = false;
            if (CacheManager.getInstance().getChapterFile(bookId, chapter) == null)
                mPresenter.getChapterRead(mChapterList.get(chapter - 1).link, chapter);
        }

        /**
         * 采用回调方法显示阅读设置栏
         */
        @Override
        public void onCenterClick() {
            LogUtils.i("onCenterClick");
            toggleReadBar();
        }


        @Override
        public void onFlip() {
            hideReadBar();
        }
    }

    class SeekBarChangeListener implements SeekBar.OnSeekBarChangeListener {

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (seekBar.getId() == seekbarFontSize.getId() && fromUser) {
                calcFontSize(progress);}
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    }

    class Receiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (mPageWidget != null) {
                if (Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())) {
                    int level = intent.getIntExtra("level", 0);
                    mPageWidget.setBattery(100 - level);
                } else if (Intent.ACTION_TIME_TICK.equals(intent.getAction())) {
                    mPageWidget.setTime(sdf.format(new Date()));
                }
            }
        }
    }
    private void calcFontSize(int progress) {
        // progress range 1 - 10
        if (progress >= 0 && progress <= 10) {
            seekbarFontSize.setProgress(progress);
            ScreenUtils.dpToPxInt(ScreenUtils.getResourcesDp(this,R.dimen.dimen_12dp));
            mPageWidget.setFontSize((int)((getResources().getDimensionPixelSize(R.dimen.dimen_12dp)) + 1.7f * progress));
        }
    }

}
